import React, { useEffect } from 'react';
import { Form, FormInstance, Select } from 'antd';
import Input from '@/components/Paste/Input';
import TextArea from '@/components/Paste/Textarea';
import WorkSpaceInput from '@/components/WorkSpaceInput';
import CommandInput, { checkRow } from '@/components/CommandInput';
import { parseJsonConfig } from '@/utils';
import { pathJoin, readFile } from '@/services/fs';

import './index.less';

const { Item } = Form;
const { Option } = Select;

const formLayout = {
  labelCol: { flex: '110px' },
  wrapperCol: { flex: 1 },
};

interface CreateFormProps {
  onLoad: (form: FormInstance) => void;
  data?: ProjectItem;
  cateList: CateItem[];
}
const CreateForm: React.FC<CreateFormProps> = ({ onLoad, data, cateList }) => {
  const [form] = Form.useForm();
  const { id } = data || {};

  const onWorkSpaceSelected = async (path: string) => {
    const file = (await readFile(
      await pathJoin(path, 'package.json'),
    )) as string;
    const { name, description, commandList } = parseJsonConfig(file, path);
    const {
      name: oname,
      code: ocode,
      description: odes,
    } = form.getFieldsValue();
    form.setFieldsValue({
      name: oname || name,
      code: ocode || name,
      description: odes || description,
      commands: commandList,
    });
  };
  useEffect(() => {
    onLoad(form);
  }, []);

  useEffect(() => {
    if (data) {
      form.setFieldsValue(data);
    } else {
      form.resetFields();
    }
  }, [data]);
  return (
    <div>
      <Form labelWrap form={form} {...formLayout}>
        <Item
          label="项目名称"
          name="name"
          rules={[
            { required: true, whitespace: true, message: '请输入项目名称' },
            { max: 200, message: '最多只能输入200个字符' },
          ]}
        >
          <Input placeholder="请输入项目名称" maxLength={200}></Input>
        </Item>
        <Item
          label="分类"
          name="cateId"
          rules={[{ required: true, message: '请输入项目名称' }]}
        >
          <Select
            size="small"
            placeholder="请选择分类"
            showSearch
            optionFilterProp="label"
          >
            {cateList.map((item) => (
              <Option key={item.id} value={item.id} label={item.name}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Item>
        <Item
          label="项目代码"
          name="code"
          rules={[
            { required: true, whitespace: true, message: '请输入项目代码' },
            { max: 20, message: '最多只能输入20个字符' },
          ]}
        >
          <Input
            disabled={!!id}
            placeholder="请输入项目代码"
            maxLength={20}
          ></Input>
        </Item>
        <Item
          label="项目描述"
          name="description"
          rules={[
            { required: true, whitespace: true, message: '请输入项目描述' },
            { max: 200, message: '最多只能输入200个字符' },
          ]}
        >
          <TextArea placeholder="请输入项目描述" maxLength={200} />
        </Item>
        <Item
          label="工作空间"
          name="workSpace"
          rules={[
            { required: true, whitespace: true, message: '请输入工作空间' },
          ]}
        >
          <WorkSpaceInput
            onChange={onWorkSpaceSelected}
            placeholder="请选择项目中的package.json文件"
          ></WorkSpaceInput>
        </Item>

        <Item
          label="调试页面"
          name="devUrl"
          rules={[{ max: 200, message: '最多只能输入200个字符' }]}
        >
          <Input placeholder="请输入调试页面URL" maxLength={200}></Input>
        </Item>
        <Item
          className="commands-item"
          labelCol={{ flex: 'none' }}
          wrapperCol={{ flex: 1 }}
          label="命令列表"
          name="commands"
          required
          rules={[
            {
              validator(_, value) {
                if (!Array.isArray(value) || value.length === 0) {
                  return Promise.reject(new Error('请配置命令'));
                }
                // 校验数据完整性和数据是否重复
                let errMsg;
                value.some((comd) => {
                  errMsg = checkRow(comd, value);
                  return !!errMsg;
                });

                if (errMsg) {
                  return Promise.reject(new Error(errMsg));
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <CommandInput />
        </Item>
      </Form>
    </div>
  );
};

export default CreateForm;
